import React, { Component } from "react";
import {
  Form,
  Input,
  Select,
  Button,
  Upload,
  Tooltip,
  message,
  DatePicker,
  Result,
} from "antd";
import { QuestionCircleOutlined, UploadOutlined } from "@ant-design/icons";
import { _addExp } from "../../../../utils/exp/index";
import { _getClassList } from "../../../../utils/class/idnex";
import { Link } from "react-router-dom";

import { style } from "./randomStyle";
import { connect } from "react-redux";

const { TextArea } = Input;
const { Option } = Select;

const { RangePicker } = DatePicker;
function randomString(len) {
  len = len || 6;
  var $chars =
    "ABCDEFGHJKMNPQRSTUVWXYZ123456789"; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
  var maxPos = $chars.length;
  var pwd = "";
  for (let i = 0; i < len; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return pwd;
}
class AddExp extends Component {
  state = {
    is_success: false,
    className: [],
    is_wordupload: false,
    is_fjupload: false,
  };
  backHandle = () => {
    this.setState({ is_success: false });
  };
  componentDidMount = () => {
    _getClassList().then((res) => {
      this.setState({ className: res.data.data });
    });
  };
  onFinish = (val) => {
    let tempData = {
      tch_id: this.props.state.data.tch_id,
      exp_name: val.exp_name,
      exp_grade: val.exp_grade,
      exp_class: val.exp_class,
      exp_msg: val.exp_msg,
      exp_time: `${val["range-picker"][0].format("YYYY-MM-DD")} 至 ${val[
        "range-picker"
      ][1].format("YYYY-MM-DD")}`,
      exp_word: val.exp_word.fileList[0].response.data.data.filename,
      exp_fj: val.exp_fj.fileList[0].response.data.data.filename,
      exp_num: randomString(6),
      exp_code: 1,
      //请求数据
      exp_style: style(),
    };
    _addExp(tempData).then((res) => {
      if (res.status === 200 && res.data.code === 0) {
        this.setState({ is_success: true });
      }
    });
  };
  onFileChangeWord = (info) => {
    const { status } = info.file;
    if (status === "uploading") {
    }
    if (status === "done") {
      // setTimeout(() => {
      message.success(`${info.file.name} 上传成功！`, 3);
      // }, 1500);
      this.setState({ is_wordupload: true });
    } else if (status === "error") {
      message.error(`${info.file.name} 上传失败！`);
    }
  };
  onFileChangeFj = (info) => {
    const { status } = info.file;
    if (status === "uploading") {
    }
    if (status === "done") {
      // setTimeout(() => {
      message.success(`${info.file.name} 上传成功！`, 3);
      // }, 1500);
      this.setState({ is_fjupload: true });
    } else if (status === "error") {
      message.error(`${info.file.name} 上传失败！`);
    }
  };
  render() {
    const layout = {
      labelCol: {
        span: 4,
      },
      wrapperCol: {
        span: 8,
      },
    };
    const tailLayout = {
      wrapperCol: {
        offset: 4,
        span: 16,
      },
    };

    const rangeConfig = {
      rules: [
        {
          type: "array",
          required: true,
          message: "请选择实验日期范围!",
        },
      ],
    };
    return (
      <div>
        {this.state.is_success ? (
          <Result
            status="success"
            title="你成功添加新的实验!"
            subTitle=""
            extra={[
              <Button type="primary" key="console">
                <Link to="/admin/t-eing">实验列表</Link>
              </Button>,
              <Button key="buy" onClick={this.backHandle}>
                返回
              </Button>,
            ]}
          />
        ) : (
          <Form
            {...layout}
            name="basic"
            initialValues={{
              remember: true,
            }}
            onFinish={this.onFinish}
          >
            <Form.Item
              label="实验名称"
              name="exp_name"
              rules={[
                {
                  required: true,
                  message: "请输入实验名称!",
                },
              ]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="年级"
              name="exp_grade"
              rules={[
                {
                  required: true,
                  message: "请输入年级!",
                },
              ]}
            >
              <Input placeholder="如2019级" />
            </Form.Item>
            <Form.Item
              label="专业班级"
              name="exp_class"
              rules={[
                {
                  required: true,
                  message: "请选择专业班级!",
                },
              ]}
            >
              <Select
                showSearch
                style={{ width: "180px" }}
                placeholder="专业班级"
                optionFilterProp="children"
                filterOption={(input, option) =>
                  option.children.toLowerCase().indexOf(input.toLowerCase()) >=
                  0
                }
              >
                {this.state.className.map((v) => (
                  <Option value={v.class_name} key={v.class_id}>
                    {v.class_name}
                  </Option>
                ))}
              </Select>
            </Form.Item>
            <Form.Item
              label="描述"
              name="exp_msg"
              rules={[
                {
                  required: true,
                  message: "请添加描述信息!",
                },
              ]}
            >
              <TextArea rows={4} placeholder="简单描述一下实验吧" />
            </Form.Item>
            <Form.Item name="range-picker" label="实验时间" {...rangeConfig}>
              <RangePicker />
            </Form.Item>
            <Form.Item
              label={
                <span>
                  实验报告&nbsp;
                  <Tooltip title="仅支持.docx">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              }
              name="exp_word"
              rules={[
                {
                  required: true,
                  message: "请上传实验报告!",
                },
              ]}
            >
              <Upload
                name="file"
                action="/api/up_word"
                listType="text"
                onChange={this.onFileChangeWord}
                accept=".docx"
                disabled={this.state.is_wordupload}
                showUploadList={true}
              >
                <Button>
                  <UploadOutlined />
                  {!this.state.is_wordupload ? "点击上传" : "已上传"}
                </Button>
              </Upload>
            </Form.Item>
            <Form.Item
              label={
                <span>
                  附件&nbsp;
                  <Tooltip title="实验中用到软件等,注:请上传压缩包">
                    <QuestionCircleOutlined />
                  </Tooltip>
                </span>
              }
              name="exp_fj"
              rules={[
                {
                  required: true,
                  message: "请上传实验所需要其他文件!",
                },
              ]}
            >
              <Upload
                name="file"
                action="/api/up_fj"
                listType="text"
                onChange={this.onFileChangeFj}
                showUploadList={false}
                disabled={this.state.is_fjupload}
              >
                <Button>
                  <UploadOutlined />
                  {!this.state.is_fjupload ? "点击上传" : "已上传"}
                </Button>
              </Upload>
            </Form.Item>

            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                创建
              </Button>
            </Form.Item>
          </Form>
        )}
      </div>
    );
  }
}

const mapStateToProps = (state) => {
  return {
    state: state.user,
  };
};
const actionCreator = {};
export default connect(mapStateToProps, actionCreator)(AddExp);
